package com.zscat.mallplus.dms.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jpay.ext.kit.PaymentKit;
import com.jpay.weixin.api.WxPayApi;
import com.zscat.mallplus.dms.entity.DmsOrder;
import com.zscat.mallplus.dms.mapper.DmsOrderMapper;
import com.zscat.mallplus.dms.service.IDeviceService;
import com.zscat.mallplus.dms.service.IDmsOrderService;
import com.zscat.mallplus.qsg.QsgDevice;
import com.zscat.mallplus.sys.mapper.SysAppletSetMapper;
import com.zscat.mallplus.ums.entity.SysAppletSet;
import com.zscat.mallplus.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class DmsOrderServiceImpl extends ServiceImpl<DmsOrderMapper, DmsOrder> implements IDmsOrderService {

    @Resource
    private DmsOrderMapper dmsOrderMapper;

    @Resource
    private IDeviceService deviceService;

    @Resource
    private SysAppletSetMapper appletSetMapper;

    @Override
    public boolean closeOrder(DmsOrder order) {
        return dmsOrderMapper.deleteById(order.getId()) > 0;
    }

    @Override
    public String calEndTime(Long deviceId) {
        QsgDevice device = deviceService.getById(deviceId);
        BigDecimal deposit = device.getDeposit();
        Integer chargingUnit = device.getChargingUnit();
        BigDecimal chargingPrice = device.getChargingPrice();
        BigDecimal oneMinutePrice = chargingPrice.divide(new BigDecimal(chargingUnit),BigDecimal.ROUND_CEILING);
        BigDecimal totalMinutes = deposit.divide(oneMinutePrice,0,  RoundingMode.HALF_UP);
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MINUTE,totalMinutes.intValue());
        Date endTime = cal.getTime();
        return DateUtil.dateToString(endTime,"yyyy/MM/dd HH:mm");
    }

    @Override
    public BigDecimal refundPartOrder(DmsOrder order) {
        SysAppletSet appletSet = appletSetMapper.selectOne(new QueryWrapper<>());
        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", appletSet.getAppid());
        params.put("mch_id", appletSet.getMchid());
        params.put("nonce_str", System.currentTimeMillis() + "");
        params.put("out_trade_no",order.getOrderSn());
        params.put("out_refund_no", System.currentTimeMillis() + "");
        params.put("total_fee", order.getPrice().multiply(new BigDecimal(100)).intValue()+"");
        BigDecimal refundMoney = calRefundMoney(order);
        params.put("refund_fee", refundMoney.toString());
        params.put("sign", PaymentKit.createSign(params, appletSet.getPaySignKey()));
        String result = WxPayApi.orderRefund(false, params, appletSet.getCertPath(), appletSet.getMchid());
        log.info("退款结果====:{}", JSON.toJSONString(result));
        return refundMoney;
    }

    @Override
    public String calEndTime(Long deviceId, int integral) {
        QsgDevice device = deviceService.getById(deviceId);
        BigDecimal balance = new BigDecimal(integral).divide(new BigDecimal(100));
        Integer chargingUnit = device.getChargingUnit();
        BigDecimal chargingPrice = device.getChargingPrice();
        BigDecimal oneMinutePrice = chargingPrice.divide(new BigDecimal(chargingUnit));
        BigDecimal totalMinutes = balance.divide(oneMinutePrice,0,  RoundingMode.HALF_UP);
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MINUTE,totalMinutes.intValue());
        Date endTime = cal.getTime();
        return DateUtil.dateToString(endTime,"yyyy/MM/dd HH:mm");
    }

    @Override
    public BigDecimal calPayMoney(DmsOrder order) {
        QsgDevice device = deviceService.getById(order.getDeviceId());
        String startTimeStr = order.getStartTime();
        Date endTime = new Date();
        String endTimeStr = DateUtil.dateToStr(endTime,"yyyy/MM/dd HH:mm");
        int diffMinutes = DateUtil.timeDiff(endTimeStr,startTimeStr);
        BigDecimal unitPrice = device.getChargingPrice();
        log.info("计费价格:{}",unitPrice);
        Integer unit = device.getChargingUnit();
        log.info("计费单元:{}",unit);
        BigDecimal oneMinutePrice = unitPrice.divide(new BigDecimal(unit),2,RoundingMode.HALF_UP);
        log.info("一分钟价格:{}",oneMinutePrice);
        BigDecimal payMoney = oneMinutePrice.multiply(new BigDecimal(diffMinutes)).setScale(2,RoundingMode.HALF_UP);
        return payMoney;
    }

    /**
     * 计算应该退款的金额
     * @param order  订单信息
     * @return 应该退款的金额
     */
    private BigDecimal calRefundMoney(DmsOrder order){
        QsgDevice device = deviceService.getById(order.getDeviceId());
        String startTimeStr = order.getStartTime();
        Date endTime = new Date();
        String endTimeStr = DateUtil.dateToStr(endTime,"yyyy/MM/dd HH:mm");
        int diffMinutes = DateUtil.timeDiff(endTimeStr,startTimeStr);
        BigDecimal unitPrice = device.getChargingPrice();
        log.info("计费价格:{}",unitPrice);
        Integer unit = device.getChargingUnit();
        log.info("计费单元:{}",unit);
        BigDecimal oneMinutePrice = unitPrice.divide(new BigDecimal(unit),2,RoundingMode.HALF_UP);
        log.info("一分钟价格:{}",oneMinutePrice);
        BigDecimal payMoney = oneMinutePrice.multiply(new BigDecimal(diffMinutes)).setScale(2,RoundingMode.HALF_UP);
        log.info("支付金额:{}",payMoney);
        BigDecimal refundMoney = (order.getPrice().subtract(payMoney)).multiply(new BigDecimal(100)).setScale(0,RoundingMode.HALF_UP);
        log.info("退款金额:{}",refundMoney);
        return refundMoney;
    }
}
